/*
 * @Author: lduoduo
 * @Date: 2021-04-20 17:11:49
 * @Last Modified by: lduoduo
 * @Last Modified time: 2021-04-23 17:05:32
 */

import { assign } from 'min-dash';

// 接收数据进行格式化后展示
export const formatPropertyToLocal = (targetBusinessObject) => {
  // console.log('formatPropertyToLocal', targetBusinessObject);
  const {
    id,
    name,
    $type,
    $attrs = {},
    documentation: doc,
    conditionExpression: condE,
    formDefinition,
    sourceRef,
  } = targetBusinessObject;
  const param = { id, name, $type, ...$attrs, formDefinition };

  // 条件表达式还原
  if (condE) {
    param.conditionExpression = condE.resource
      .replace('<![CDATA[${', '')
      .replace('}]]>', '')
      .replace('${', '')
      .replace('}', '');
  }

  // 节点描述
  if (doc && doc[0]) {
    const { text } = doc[0];
    param.documentation = text;
  }

  // 默认路径还原
  if (/SequenceFlow/.test($type)) {
    param.isDefaultFlow = sourceRef.default === targetBusinessObject;
  }

  return param;
};

// 提交数据格式化
export const formatPropertyToRemote = (d, targetBusinessObject, modeler, shape) => {
  // console.log('formatPropertyToRemote', d);

  const [k] = Object.keys(d);

  // 引用表单处理
  if (k === 'formDefinition') {
    // 新建属性字段
    const newPropertyObject = modeler.moddle.create(`activiti:FormDefinition`, d[k]);
    const { id, key, name } = d[k];

    // return assign(targetBusinessObject, { [k]: newPropertyObject, formKey: key });
    return [{ [k]: newPropertyObject, formKey: key }];
  }

  // 条件表达式处理
  if (k === 'conditionExpression') {
    const newCondition = modeler.moddle.create('bpmn:FormalExpression', {
      resource: '<![CDATA[${' + d[k] + '}]]>',
    });

    return [{ [k]: newCondition }];
  }

  // 默认路径
  if (k === 'isDefaultFlow') {
    const { sourceRef: { id } = {} } = targetBusinessObject;

    const shape = modeler.elementRegistry.get(id);
    return [{ default: targetBusinessObject }, shape];
  }

  if (k === 'documentation') {
    const newPropertyObject = modeler.moddle.create(`bpmn:Documentation`, { text: d[k] });
    return [{ [k]: [newPropertyObject] }];
  }

  return [d];
};
